/**
 * 该类为HTTP连接工具类;
 * 现在仅支持get/post两种方式;
 */
// import { cc.vv.GLDefine } from "./../Config/GLDefine";
// import { cc.vv.GLSDKMgr } from "./../lib/GLSDKMgr";

class GLHttpUtils {
  Max_Try_Time: number = 4; //连接失败再次尝试次数;
  _reqListTimes: object = {};

  init() {
    this._reqListTimes = {};
  }

  /**
 * @description get提交，无数据校验
 * @param {*} url 
 * @param {*} param 
 * @param {*} callBack 
 * @param {*} error 
 */
  httpGet(url, paraminput, callBack) {
    cc.log("excute  httpGet")
    var xhr = cc.loader.getXMLHttpRequest();
    var str = ''
    if (paraminput) {
      str = "?";
      for (var k in paraminput) {
        if (str != "?") {
          str += "&";
        }
        str += k + "=" + paraminput[k];
      }
    }
    var extraUrl = url + str;
    var xhr = new XMLHttpRequest();
    xhr.onload = function () {
      if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 400) {
        var response = xhr.responseText;;
        callBack(response);
      } else {
        console.log("222")
      }
    };
    xhr.onerror = function (e) {
      console.log("e  is ", e)
    };
    xhr.open("GET", extraUrl, true);
    xhr.setRequestHeader(
      "Content-Type",
      "application/x-www-form-urlencoded;charset=UTF-8"
    );
    xhr.send();
  }
  /**
   * HTTP get;
   * @param {*} url
   * @param {*Text Data/Binary Data} dataType
   * @param {*} callback
   */
  httpGets(url, isSDK, dataType, callback, responseType = "arraybuffer") {
    console.log("httpGets: " + url);
    // var ss = url.substr(7).split(":");
    // var ip = ss[0];
    var _url = url;
    if (isSDK) {
      _url = this.getUrl(url);
    }
    if (!_url) {
      if (callback) {
        callback(false);
      }
      return;
    }

    var xhr = new XMLHttpRequest();
    var self = this;
    xhr.onload = function () {
      self.getRequestEnd(xhr, url, isSDK, dataType, callback);
    };
    xhr.onerror = function (e) {
      self.getError(callback, url);
    };
    //xhr.responseType = responseType;
    xhr.open("GET", _url, true);

    //  var _dd = url.substr(7);

    //xhr.setRequestHeader("host", "bg.lmfurn.com:81");
    xhr.setRequestHeader(
      // "User-Agent",
      "Content-Type",
      "application/x-www-form-urlencoded;charset=UTF-8"
    );

    xhr.send();
  }
  getError(callback, url) {
    if (callback) {
      callback(false, url);
    }
  }
  /**
   * response dispose;
   */
  getRequestEnd(xhr, url, isSdk, dataType, callback) {
    var isOK = false;
    if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 400) {
      var response = null;
      var responseType = cc.vv.GLDefine.EXHRDataType.Text;
      if (dataType == cc.vv.GLDefine.EXHRDataType.Binary) {
        response = xhr.response;
        responseType = cc.vv.GLDefine.EXHRDataType.Binary;
      } else {
        response = xhr.responseText;
        // responseType = "text";
      }
      isOK = true;
      callback(isOK, response);
    } else {
      this.getRequestFailed(url, isSdk, dataType, callback);
    }
  }
  /**
   * failed dispose ;
   */
  getRequestFailed(url, isSdk, dataType, callback) {
    if (!this._reqListTimes[url]) {
      this._reqListTimes[url] = 0;
    }
    if (this._reqListTimes[url] >= this.Max_Try_Time) {
      //达到最大尝试次数;
      if (callback) {
        callback(false);
      }
    } else {
      this._reqListTimes[url]++; //尝试次数自加;
      console.log(
        "RequestFailed url: " + url + " trytime: " + this._reqListTimes[url]
      );
      this.httpGets(url, isSdk, dataType, callback);
    }
  }
  /**
   * serialize Post Data;
   */
  serializePost(params) {
    var str = "";
    var i = 0;
    for (var key in params) {
      if (i++ != 0) {
        str += "&";
      }
      str += key + "=" + params[key];
    }
    return str;
  }
  /**
   * HTTP post;
   * @param {*} url
   * @param {*custom post data} params
   * @param {*} callback
   */
  httpPost(url, params, callback) {
    // var ss = url.substr(7).split(":");
    // var ip = ss[0];
    var _url = this.getUrl(url);
    if (!_url) {
      if (callback) {
        callback(false);
      }
      return;
    }

    var xhr = new XMLHttpRequest();
    xhr.onload = function () {
      var response = "";
      if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 400) {
        console.log("get--responseok---url:" + url);
        response = xhr.responseText;
      }
      if (callback) {
        callback(response);
      }
    };
    xhr.open("POST", _url, true);
    // var _dd = url.substr(7);
    // xhr.setRequestHeader("host", "bg.lmfurn.com:81");
    xhr.setRequestHeader(
      "Content-Type",
      "application/x-www-form-urlencoded;charset=UTF-8"
    );

    xhr.timeout = 5000; // 5 seconds for timeout

    xhr.send(this.serializePost(params));
  }

  getUrl(url) {
    var ss = url.substr(7).split(":");
    var ip = ss[0];
    var ss1 = ss[1].split("/");
    var port = ss1[0];
    var cfg = cc.vv.GLSDKMgr.getServerIpAndPort(ip, parseInt(port));

    if (!cfg) {
      return;
    }

    var _url = "";

    _url = "http://" + cfg.ip + ":" + cfg.port;
    for (var i = 1; i < ss1.length; i++) {
      _url += "/" + ss1[i];
    }

    console.log("____url = " + _url);
    return _url;
  }

  httpPost1(url, params, callback) {
    var _url = this.getUrl(url);
    if (!_url) {
      if (callback) {
        callback(
          JSON.stringify({
            err: "URL错误"
          })
        );
      }
      return;
    }
    var xhr = new XMLHttpRequest();

    console.log("____post_url =" + _url);

    xhr.open("POST", _url, true);

    //console.log("____host_ip=" + _dd);
    //xhr.setRequestHeader("host", _dd);
    //xhr.setRequestHeader("X-Forward-For", client_ip);
    xhr.setRequestHeader(
      "Content-Type",
      "application/x-www-form-urlencoded;charset=UTF-8"
    );

    xhr.timeout = 5000; // 5 seconds for timeout
    // 请求完成。
    xhr.onload = function () {
      console.log("___http:onload___", url);
      var response = "";
      if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 400) {
        console.log("get--responseok---url:" + url);
        response = xhr.responseText;
        this._reqListTimes[url] = 0;
        if (callback) {
          callback(response);
        }
      } else {
        this.requestFailed(url, params, callback);
      }
    }.bind(this);

    //  超时
    xhr.ontimeout = function (e) {
      console.log("timeOut : e = " + JSON.stringify(e));
      this.requestFailed(url, params, callback);
    }.bind(this);

    // 产生错误。
    xhr.onerror = function (e) {
      console.log("error : e = " + JSON.stringify(e));
      this._reqListTimes[url] = 0;
      if (callback) {
        callback(
          JSON.stringify({
            err: "网络错误"
          })
        );
      }
    }.bind(this);

    console.log("___send = " + JSON.stringify(params));
    xhr.send(JSON.stringify(params));
  }

  requestFailed(url, params, callback) {
    if (!this._reqListTimes[url]) {
      this._reqListTimes[url] = 0;
    }
    if (this._reqListTimes[url] >= this.Max_Try_Time) {
      //达到最大尝试次数;
      this._reqListTimes[url] = 0;
      if (callback) {
        callback(
          JSON.stringify({
            err: "网络超时"
          })
        );
      }
    } else {
      this._reqListTimes[url]++; //尝试次数自加;
      console.log(
        "RequestFailed url: " + url + " trytime: " + this._reqListTimes[url]
      );
      this.httpPost1(url, params, callback);
    }
  }

  // 文件上传
  on_upload_file(allpathname) {
    // 测试只能在native平台
    var fileData = jsb.fileUtils.getDataFromFile(allpathname);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', cc.vv.GLConfig.storageImgWebPath + allpathname);
    xhr.setRequestHeader('Content-Type', 'application/octet-stream');
    xhr.send(fileData);
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          var m = xhr.responseText;
          var response = xhr.responseText.substring(0, 100) + "...";
          cc.log(m);
        }
      }
    }
    //  
    xhr.onload = function (e) {
      console.log("onload on_upload_file: e = " + JSON.stringify(e));
    }.bind(this);
    //
    xhr.onloadstart = function (e) {
      console.log("onload onloadstart: e = " + JSON.stringify(e));
    }.bind(this);
    //  超时
    xhr.ontimeout = function (e) {
      console.log("timeOut : e = " + JSON.stringify(e));
    }.bind(this);

    // 产生错误。
    xhr.onerror = function (e) {
      console.log("error : e = " + JSON.stringify(e));
    }.bind(this);

  }

}

export let glHttpUtils: GLHttpUtils = new GLHttpUtils(); //
